import os
import webapp2
import gdata.docs.client
import gdata.gauth
import jinja2
import ConfigParser
import diff_match_patch.diff_match_patch

import config

from google.appengine.api import users
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import mail
# jinja_environment = jinja2.Environment(
#     loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

# Configure gdata
config_parser = ConfigParser.RawConfigParser()
config_parser.read('config.cfg')
SETTINGS = {
  'APP_NAME': config_parser.get('gdata_settings', 'APP_NAME'),
'CONSUMER_KEY': config_parser.get('gdata_settings', 'CONSUMER_KEY'),
'CONSUMER_SECRET': config_parser.get('gdata_settings', 'CONSUMER_SECRET'),
  'SCOPES': [config_parser.get('gdata_settings', 'SCOPES')]
}

gdocs = gdata.docs.client.DocsClient(source = SETTINGS['APP_NAME'])
gdiff = diff_match_patch.diff_match_patch()


class Fetcher(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()

    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(scopes, oauth_callback,
        consumer_key, consumer_secret)

    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(request_token, request_token_key)

    approvalPageUrl = request_token.generate_authorization_url()

    templateValues = {
      'approvalPageUrl': approvalPageUrl,
    }
    template = config.jinja_environment.get_template('templates/step1.html')
    self.response.out.write(template.render(templateValues))


class FetchCollection(webapp2.RequestHandler):
  @login_required
  def get(self):
    access_token_key = 'access_token_%s' % users.get_current_user().user_id()
    access_token = gdata.gauth.AeLoad(access_token_key)
    gdocs.auth_token = access_token

    feed = gdocs.GetResources(uri='/feeds/default/private/full/-/folder')

    folders = []
    for entry in feed.entry:
      folder = {
        'title': entry.title.text,
        'id': entry.resource_id.text
      }
      folders.append(folder)

    templateValues = {
      'entries': "",
      'folders': folders
    }
    template = config.jinja_environment.get_template('templates/collections.html')
    self.response.out.write(template.render(templateValues))


class RequestRawRevision(webapp2.RequestHandler):
  @login_required
  def get(self):
    access_token_key = 'access_token_%s' % users.get_current_user().user_id()
    access_token = gdata.gauth.AeLoad(access_token_key)
    gdocs.auth_token = access_token
    id = self.request.get('id')

    # TODO(jordan): Figure out how to catch exception with invalid resource
    resource = gdocs.GetResourceById(id)
    revisions = gdocs.GetRevisions(resource)

    revisionLinks = []
    for revision in revisions.entry:
      revisionLink = revision.GetSelfLink().href
      revisionLinks.append(revisionLink)

    templateValues = {
      'revisionLinks': revisionLinks,
    }
    template = config.jinja_environment.get_template('templates/raw.html')
    self.response.out.write(template.render(templateValues))


class RequestARawRevision(webapp2.RequestHandler):
  @login_required
  def get(self):
    revision = gdocs.GetRevisionBySelfLink(self.request.get('revisionLink'))
    revisionLink = gdocs.DownloadRevisionToMemory(revision)
    self.response.out.write(revisionLink)


class RequestTokenCallback(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()

    # Authorize the request token to be an access token
    request_token_key = 'request_token_%s' % current_user.user_id()
    request_token = gdata.gauth.AeLoad(request_token_key)
    gdata.gauth.authorize_request_token(request_token, self.request.uri)

    # Create the long lived access token from the request token
    gdocs.auth_token = gdocs.get_access_token(request_token)
    access_token = request_token

    # Store the access token
    access_token_key = 'access_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(access_token, access_token_key)

    # TODO(someone?): Find out what webap2.redirect does
    webapp2.redirect('step3')
    template = config.jinja_environment.get_template('templates/step2.html')
    self.response.out.write(template.render())


class MainPage(webapp2.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      template = config.jinja_environment.get_template('templates/indexUser.html')
      templateValues = {
        'nickname': user.nickname(),
        'logoutLink': users.create_logout_url(self.request.uri),
      }
    else:
      template = config.jinja_environment.get_template('templates/indexNoUser.html')
      templateValues = {
        'loginLink': users.create_login_url(self.request.uri),
      }
    self.response.out.write(template.render(templateValues))
    
class TestNaren(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()

    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(scopes, oauth_callback,
        consumer_key, consumer_secret)

    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(request_token, request_token_key)

    approvalPageUrl = request_token.generate_authorization_url()

    templateValues = {
      'approvalPageUrl': approvalPageUrl,
    }
    template = config.jinja_environment.get_template('templates/TestNaren.html')
    self.response.out.write(template.render(templateValues))

class TestTristan(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()

    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(scopes, oauth_callback,
        consumer_key, consumer_secret)

    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(request_token, request_token_key)

    approvalPageUrl = request_token.generate_authorization_url()

    templateValues = {
      'approvalPageUrl': approvalPageUrl,
    }
    template = config.jinja_environment.get_template('templates/TestTristan.html')
    self.response.out.write(template.render(templateValues))
    message = mail.EmailMessage(sender="Example.com Support <tristan.d.biles@gmail.com>",
                            subject="Your account has been approved")

    message.to = "Albert Johnson <tbawaz@gmail.com>"
    message.body = """
    Dear Albert:
    
    Your example.com account has been approved.  You can now visit
    http://www.example.com/ and sign in using your Google Account to
    access new features.
    
    Please let us know if you have any questions.
    
    The example.com Team
    """
    
    message.send()
    # look to change templateValues with appropriate 
    # method to send out an email to "tbawaz@gmail.com"
    
class TestFoster(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()

    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(scopes, oauth_callback,
        consumer_key, consumer_secret)

    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(request_token, request_token_key)

    approvalPageUrl = request_token.generate_authorization_url()

    templateValues = {
      'approvalPageUrl': approvalPageUrl,
    }
    template = config.jinja_environment.get_template('templates/TestFoster.html')
    self.response.out.write(template.render(templateValues))
    
class TestHelio(webapp2.RequestHandler):
  @login_required
  def get(self):
    current_user = users.get_current_user()
    
    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(
        scopes, oauth_callback, consumer_key, consumer_secret)
    
    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(
        request_token, request_token_key)
    
    approvalPageUrl = request_token.generate_authorization_url()
    
    templateValues = {
        'approvalPageUrl': approvalPageUrl,}
    template = config.jinja_environment.get_template('templates/TestHelio.html')
    self.response.out.write(template.render(templateValues))
    
    
class TestJonathan(webapp2.RequestHandler):
  #@login_required
  def get(self):
    import sys
    import drive_appengine.httplib2
    sys.path.append("drive_appengine/")
    import drive_appengine.scapes_revision_drive as srevision_drive
    import drive_appengine.scapes_file_drive     as sfile_drive
    from apiclient import discovery
    from google.appengine.api import memcache

    with open("drive_appengine/client_secrets.json") as f:
      import json
      data = json.loads(f.read())
      print data
      CLIENT_ID     = data[u"web"][u"client_id"]
      CLIENT_SECRET = data[u"web"][u"client_secret"]
      
    ######
    import httplib2
    import pprint

    from apiclient.discovery import build
    from apiclient.http import MediaFileUpload
    from oauth2client.client import OAuth2WebServerFlow

    # Copy your credentials from the console
    CLIENT_ID = '551548476927-h19sqjvvej0du0f6a487u0iac6u3dh7k.apps.googleusercontent.com'
    CLIENT_SECRET = 'Lu7PouJg0QSxYzaWoJUl_eqD'

    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

    # Redirect URI for installed apps
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

    # Path to the file to upload
    FILENAME = 'document.txt'

    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    # code = raw_input('Enter verification code: ').strip()
    code = "4/1lDr85ZH4CnHTofVYh3AXb5TWw5Y.MoHnu-2zyIYbmmS0T3UFEsOGgyWJhAI"
    credentials = flow.step2_exchange(code)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)

    # Insert a file
    media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
    body = {
      'title': 'My document',
      'description': 'A test document',
      'mimeType': 'text/plain'
    }

    file = drive_service.files().insert(body=body, media_body=media_body).execute()
    pprint.pprint(file)

    ####
    http = drive_appengine.httplib2.Http(memcache)
    service = discovery.build('drive', 'v2', http=http)

    print sfile_drive.retrieve_all_files(service)

    current_user = users.get_current_user()

    scopes = SETTINGS['SCOPES']
    oauth_callback = 'http://%s/step2' % self.request.host
    consumer_key = SETTINGS['CONSUMER_KEY']
    consumer_secret = SETTINGS['CONSUMER_SECRET']
    request_token = gdocs.get_oauth_token(
        scopes, oauth_callback, consumer_key, consumer_secret)

    request_token_key = 'request_token_%s' % current_user.user_id()
    gdata.gauth.ae_save(
        request_token, request_token_key)

    approvalPageUrl = request_token.generate_authorization_url()

    templateValues = {
        'approvalPageUrl': approvalPageUrl,}
    template = config.jinja_environment.get_template('templates/TestJonathan.html')

    self.response.out.write(template.render(templateValues))

class GoogleWebmasterVerify(webapp2.RequestHandler):
  def get(self):
    template = config.jinja_environment.get_template('google910e6da758dc80f1.html')
    self.response.out.write(template.render())
